package com.dld.android.view;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.dld.android.util.LogUtils;

import java.util.ArrayList;

public class SegmentControl extends LinearLayout {
	private SegmentControlAdapter adapter;
	private ArrayList<View> childs = new ArrayList<View>();
	private View focused;

	public SegmentControl(Context paramContext, AttributeSet paramAttributeSet) {
		super(paramContext, paramAttributeSet);
	}

	public void changeFocus(int paramInt) {
		changeFocus((View) this.childs.get(paramInt), this.focused);
	}

	protected void changeFocus(View paramView1, View paramView2) {
		if ((this.adapter != null) && (!this.adapter.disable()))
			if (paramView2 != null) {
				if (paramView1 != this.focused) {
					paramView2.setClickable(true);
					this.adapter.onBlur(paramView2, this.childs
							.indexOf(paramView2));
					this.adapter.onFocus(paramView1, this.childs
							.indexOf(paramView1));
				}
			} else {
				this.focused = paramView1;
				this.focused.setClickable(false);
			}
	}

	public SegmentControlAdapter getAdapter() {
		return this.adapter;
	}

	public int getFocusIndex() {
		return this.childs.indexOf(this.focused);
	}

	public void notifyDataChanged() {
		setAdapter(this.adapter);
	}

	protected void onFinishInflate() {
		super.onFinishInflate();
	}

	public boolean onInterceptTouchEvent(MotionEvent paramMotionEvent) {
		int x = (int) paramMotionEvent.getX();
		int y = (int) paramMotionEvent.getY();
		int count = getChildCount();
		for (int i = 0; i < count; i++) {
			View child = getChildAt(i);
			if (new Rect(child.getLeft(), child.getTop(), child.getRight(),
					child.getBottom()).contains(x, y)) {
				if (child != this.focused)
					changeFocus(child, this.focused);
				else
					this.adapter.onBack();
			}

		}
		return true;
	}

	public void setAdapter(SegmentControlAdapter paramSegmentControlAdapter) {
		this.adapter = paramSegmentControlAdapter;
		int i = paramSegmentControlAdapter.getDefaultFocusIndex();
		int j = paramSegmentControlAdapter.getCount();
		for (int k = 0; k < j; k++) {
			View localView = paramSegmentControlAdapter.getView(k);
			this.childs.add(localView);
			localView.setFocusable(false);
			if (k == i) {
				changeFocus(localView, this.focused);
			}
		}
	}
}
